const redis = require('redis');
const {v4: uuidv4} = require('uuid');

const redisConfig = require('../config/index').redisConfig;

const client = redis.createClient(redisConfig)

module.exports = {
    client,
    newClient: function() {
        return redis.createClient(redisConfig)
    },
    setLock: async function(key, ttl) {
        return new Promise((resolve, reject) => {
            if (!key) {
                return reject('缺少参数');
            }
            ttl = ttl || 3;
            if (ttl <= 0) {
                return reject('参数错误');
            }
            let value = uuidv4();
            client.set(key, value, 'EX', ttl, 'NX', (err, reply) => {
                if (!err && reply === 'OK') {
                    return resolve({key, value});
                }
                err = err || key + '处于锁定状态';
                reject(err);
            });
        });
    },

    clearLock: async function(key) {
        return new Promise((resolve, reject) => {
            if (!key) return resolve();
            if (!key) return reject('参数错误');
            client.del(key, err => {
                if (err) {
                    return reject(err);
                }
                resolve();
            });
        });
    },

    set: async function() {
        let args = arguments;
        return new Promise((resolve, reject) => {
            client.set(...args, err => {
                if (err) return reject(err);
                resolve();
            });
        });
    },

    get: async function() {
        let args = arguments;
        return new Promise((resolve, reject) => {
            client.get(...args, (err, res) => {
                if (err) return reject(err);
                resolve(res);
            });
        });
    },

    del: async function() {
        let args = arguments;
        return new Promise((resolve, reject) => {
            client.del(...args, (err, res) => {
                if (err) return reject(err);
                resolve(res);
            });
        });
    }
};
